/**
 * 438. 找到字符串中所有字母异位词
 * https://leetcode-cn.com/problems/find-all-anagrams-in-a-string/
 */
const { displayBaseArray } = require('../../libs/public');

/**
 * @param {string} s
 * @param {string} p
 * @return {number[]}
 */
function findAnagrams(s, p) {
  const sign = new Array(128).fill(-1);
  let length = 0;
  for (let i = 0; i < p.length; i += 1) {
    const code = p.charCodeAt(i);
    if (sign[code] < 0) {
      sign[code] = 0;
    }
    sign[code] += 1;
    length += 1;
  }
  let start = -1;
  const result = [];
  for (let i = 0; i < s.length; i += 1) {
    const code = s.charCodeAt(i);
    if (sign[code] >= 0) {
      if (sign[code] > 0) {
        if (start < 0) {
          start = i;
        }
        sign[code] -= 1;
        length -= 1;
      } else {
        // eslint-disable-next-line no-lonely-if
        if (start >= 0) {
          for (let j = start; j < i && sign[code] === 0; j += 1) {
            sign[s.charCodeAt(j)] += 1;
            length += 1;
            start += 1;
          }
          sign[code] -= 1;
          length -= 1;
        }
      }
      if (!length && start >= 0) {
        result.push(start);
      }
    } else {
      // eslint-disable-next-line no-lonely-if
      if (start >= 0) {
        for (let j = start; j < i; j += 1) {
          sign[s.charCodeAt(j)] += 1;
          length += 1;
        }
        start = -1;
      }
    }
  }
  return result;
}

console.log(displayBaseArray(findAnagrams('cbaebabacd', 'abc')) === '[0,6]');
console.log(displayBaseArray(findAnagrams('abab', 'ab')) === '[0,1,2]');
